var loggedin = false;
var first = '';
var last = '';
var username = '';

function showLogin()
{
	var myAjax = new Ajax.Request('login.html', {
		method: 'get',
		onComplete: function(request){
			$('nav_login').update(request.responseText);
			$('login_close').observe('click', hideLogin);
			$('submit').observe('click', checkLogin);
		}
	});

}
function hideLogin()
{
	$('nav_login').update('<a href="#" onClick="showLogin();">Login</a>');
}
function checkLogin()
{
	user = $('username').value;
	password = $('password').value;

	$('password').value = '';

	if (user != '' && password != '') {
		hashed = hex_md5(password);

		var myAjax = new Ajax.Request('login.php', {
			method: 'get',
			parameters: {username: user, hash: hashed, task: 'checklogin'},
			onComplete: function(request){
				rtn = request.responseText.evalJSON();

				if (rtn.success) {
					loggedIn(rtn);
				}
				else {
					$('messages').addClassName('error');
					$('messages').update(rtn.message);
				}
			}
		});
	}
}


function loggedIn(data) {
	showlogin();
	loggedin = true;
	first = data.first;
	last = data.last;
	username = data.username;

	showUserResults();
}

function showlogin() {
	$('nav_login').update('<a href="#" onClick="showLogout();">Logout</a>');
	$('nav_user').update('<a href="#" onClick="showUserResults();">User Page</a>');
	$('messages').removeClassName('error');
	$('messages').update('');

}

function showLogout() {
	loggedin = false;
	first = '';
	last = '';
	username = '';

	var myAjax = new Ajax.Request('logout.php', {
		method: 'get',
		onComplete: function(request){
			$('nav_login').update('<a href="#" onClick="showLogin();">Login</a>');
			$('nav_user').update('&nbsp');
			getPage('species_list.html', 'main');
		}
	});
}

function showUserResults() {
	if (loggedin == true) {
		var myAjax = new Ajax.Request('stats_user.php', {
			method: 'get',
			onComplete: function(request) {
				$('main').update(request.responseText);
				initialize_user_map(username);
			}
		});
	}
	else {
		showLogin();
	}
}

function getPage(url, target) {
	var myAjax = new Ajax.Request(url, {
		method: 'get',
		onComplete: function(request) {
			$(target).update(request.responseText);
		}
	});

}
